﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;

public class Common
{
	public static string Query(string item, string value = "") { return HttpContext.Current.Request.QueryString[item] ?? value; }

	public static string Action { get { return Query("do"); } }
	public static bool IsAdd { get { return "add".Equals(Action); } }
	public static bool IsEdit { get { return "edit".Equals(Action); } }
	public static bool IsSave { get { return "save".Equals(Action); } }
	public static bool IsDelete { get { return "delete".Equals(Action); } }

	public static int Start { get { string start = Query("start"); return "".Equals(start) ? 0 : int.Parse(start); } }
	public static int Limit { get { string limit = Query("limit"); return "".Equals(limit) ? 0 : int.Parse(limit); } }

	public static int Id { get { return int.Parse("0" + Query("id")); } }

	public static DataContext.Account User { get { return HttpContext.Current.Session["User"] as DataContext.Account; } }
	public static void CheckLogin() { if (User == null) { HttpContext.Current.Response.Write("<a target='_top' href='../admin.aspx'>登录超时。请重新登录。</a>"); HttpContext.Current.Response.End(); } }

	public static void SaveThumbnail(Stream stream, string guid)
	{
		try
		{
			SaveThumbnail(stream, new Size(1024, 768), HttpContext.Current.Server.MapPath("~/App_Data/Products/" + guid), ImageFormat.Jpeg);
			SaveThumbnail(stream, new Size(360, 270), HttpContext.Current.Server.MapPath("~/upload/products/" + guid + ".jpg"), ImageFormat.Jpeg);
		} catch (Exception ex)
		{
			throw ex;
		}
	}
	public static void SaveThumbnail(Stream stream, Size size, string path, ImageFormat format)
	{
		Bitmap image = (Bitmap)Image.FromStream(stream);
		int width = image.Width, height = image.Height;

		if (width > size.Width)
		{
			height = height * size.Width / width;
			width = size.Width;
		}
		if (height > size.Height)
		{
			width = width * size.Height / height;
			height = size.Height;
		}

		Bitmap bitmap = new Bitmap(width, height);
		Graphics graphic = Graphics.FromImage(bitmap);
		graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
		graphic.SmoothingMode = SmoothingMode.HighQuality;
		graphic.Clear(Color.Transparent);
		graphic.DrawImage(image, new Rectangle(0, 0, width, height), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
		try
		{
			bitmap.Save(path, format);
		} catch (Exception ex)
		{
			throw ex;
		} finally
		{
			image.Dispose();
			bitmap.Dispose();
			graphic.Dispose();
		}
	}
}
